# encoding: utf-8
"""
@author:  liaoxingyu
@contact: sherlockliao01@gmail.com
"""

import torch.nn.functional as F
from mmcv.runner import BaseModule

from .triplet_loss import TripletLoss, CrossEntropyLabelSmooth
from .center_loss import CenterLoss
import warnings

import torch
import torch.nn as nn


import torch.nn.functional as F



from mmdet.core.anchor.point_generator import MlvlPointGenerator
from mmcv.cnn import ConvModule, bias_init_with_prob, normal_init
from mmdet.models.dense_heads.anchor_free_head_reid import AnchorFreeHeadReid
from mmdet.models.dense_heads.labeled_matching_layer import LabeledMatchingLayer, LabeledMatchingLayerNorm
from mmdet.models.dense_heads.unlabeled_matching_layer import UnlabeledMatchingLayer, UnlabeledMatchingFullLayer

INF = 1e8

import torch
from torch import nn
from torch.nn import init
from collections import OrderedDict
from mmdet.core import multi_apply

class fby_af_loss1(BaseModule):

    def __init__(self,
                 center_sampling=True,
                 center_sample_radius=1.5,
                 unlabel_full=False,
                 unlabel_weight=10,
                 temperature=1,
                 num_person = 483,
                 queue_size = 500,
                 label_norm = True,
                 init_cfg = None
                 ):
        super(fby_af_loss1, self).__init__(init_cfg)
        self.center_sampling = center_sampling
        self.center_sample_radius = center_sample_radius
        self.regress_ranges = [(-1,INF)]
        self.num_person = num_person
        self.queue_size = queue_size
        self.label_norm = label_norm
        self.unlabel_full = unlabel_full
        self.unlabel_weight = unlabel_weight
        self.temperature = temperature
        self.prior_generator = MlvlPointGenerator((8,))
        self.in_channels = 256
        self.box = (126.0,254.0)
        self.strides = [8,]
        self.feat_channels = 256

        self._init_layers()

    def _init_layers(self):
        if self.label_norm:
            self.labeled_matching_layer = LabeledMatchingLayerNorm(num_persons=self.num_person, feat_len=self.in_channels)
        else:
            self.labeled_matching_layer = LabeledMatchingLayer(num_persons=self.num_person,
                                                               feat_len=self.in_channels)  # for mot17half
        if self.unlabel_full:
            self.unlabeled_matching_layer = UnlabeledMatchingFullLayer(queue_size=self.queue_size, feat_len=self.in_channels)
        else:
            self.unlabeled_matching_layer = UnlabeledMatchingLayer(queue_size=self.queue_size, feat_len=self.in_channels)
    def loss(self,
             reid_feats,
             gt_ids
             ):

        featmap_sizes = []
        featmap_sizes.append(reid_feats.size()[-2:])
        all_level_points = self.prior_generator.grid_priors(featmap_sizes)


        import numpy as np
        gt_ids1 = []
        for iii in gt_ids:
            list1 = []
            list1.append(iii)
            gt_ids1.append(torch.tensor(list1).to(torch.device(gt_ids.device)))

        gt_bboxes = []
        for i in range(len(gt_ids)):
            gt_bboxes.append(
                torch.tensor([1, 1, self.box[0], self.box[1]]).unsqueeze(0).to(torch.device(gt_ids.device)))

        ids = self.get_targets(all_level_points, gt_bboxes, gt_ids1)
        ids = ids[0]
        posind= (ids > 0).nonzero().reshape(-1)

        flatten_reid = reid_feats.permute(0, 2, 3, 1).reshape(-1, self.feat_channels)
        flatten_reid = flatten_reid[posind]
        pos_reid = F.normalize(flatten_reid)
        pos_reid_ids = ids[posind]
        # reid oim loss
        labeled_matching_scores = self.labeled_matching_layer(pos_reid, pos_reid_ids)
        labeled_matching_scores *= self.temperature
        # unlabeled_matching_scores = self.unlabeled_matching_layer(pos_reid, pos_reid_ids)
        # unlabeled_matching_scores = unlabeled_matching_scores * self.unlabel_weight
        # matching_scores = torch.cat((labeled_matching_scores, unlabeled_matching_scores), dim=1)
        pid_labels = pos_reid_ids.clone()
        pid_labels[pid_labels == -2] = -1

        p_i = F.softmax(labeled_matching_scores, dim=1)
        focal_p_i = (1 - p_i) ** 2 * p_i.log()
        loss_oim = F.nll_loss(focal_p_i, pid_labels, reduction='none', ignore_index=-1)

        return loss_oim.mean()

    def get_targets(self, points, gt_bboxes_list, gt_ids_list):


        assert len(points) == len(self.regress_ranges)
        num_levels = len(points)
        # expand regress ranges to align with points
        expanded_regress_ranges = [
            points[i].new_tensor(self.regress_ranges[i])[None].expand_as(
                points[i]) for i in range(num_levels)
        ]
        # concat all levels points and regress ranges
        concat_regress_ranges = torch.cat(expanded_regress_ranges, dim=0)

        concat_points = torch.cat(points, dim=0)

        # the number of points per img, per lvl
        num_points = [center.size(0) for center in points]

        # get labels and bbox_targets of each image
        ids_list, _ = multi_apply(
            self._get_target_single,
            gt_bboxes_list,
            gt_ids_list,
            points=concat_points,
            regress_ranges=concat_regress_ranges,
            num_points_per_lvl=num_points)

        # split to per img, per level
        ids_list = [ids.split(num_points, 0) for ids in ids_list]
        # concat per level image
        concat_lvl_ids = []
        for i in range(num_levels):

            concat_lvl_ids.append(
                torch.cat([ids[i] for ids in ids_list]))

        return concat_lvl_ids

    def _get_target_single(self, gt_bboxes, gt_ids, points, regress_ranges,
                           num_points_per_lvl):
        """Compute regression and classification targets for a single image."""
        num_points = points.size(0)
        num_gts = gt_ids.size(0)

        areas = (gt_bboxes[:, 2] - gt_bboxes[:, 0]) * (
                gt_bboxes[:, 3] - gt_bboxes[:, 1])
        # TODO: figure out why these two are different
        # areas = areas[None].expand(num_points, num_gts)
        areas = areas[None].repeat(num_points, 1)
        regress_ranges = regress_ranges[:, None, :].expand(
            num_points, num_gts, 2)
        gt_bboxes = gt_bboxes[None].expand(num_points, num_gts, 4)
        xs, ys = points[:, 0], points[:, 1]
        xs = xs[:, None].expand(num_points, num_gts)
        ys = ys[:, None].expand(num_points, num_gts)

        left = xs - gt_bboxes[..., 0]
        right = gt_bboxes[..., 2] - xs
        top = ys - gt_bboxes[..., 1]
        bottom = gt_bboxes[..., 3] - ys
        bbox_targets = torch.stack((left, top, right, bottom), -1)

        if self.center_sampling:
            # condition1: inside a `center bbox`
            radius = self.center_sample_radius
            center_xs = (gt_bboxes[..., 0] + gt_bboxes[..., 2]) / 2
            center_ys = (gt_bboxes[..., 1] + gt_bboxes[..., 3]) / 2
            center_gts = torch.zeros_like(gt_bboxes)
            stride = center_xs.new_zeros(center_xs.shape)

            # project the points on current lvl back to the `original` sizes
            lvl_begin = 0
            for lvl_idx, num_points_lvl in enumerate(num_points_per_lvl):
                lvl_end = lvl_begin + num_points_lvl
                stride[lvl_begin:lvl_end] = self.strides[lvl_idx] * radius
                lvl_begin = lvl_end

            x_mins = center_xs - stride
            y_mins = center_ys - stride
            x_maxs = center_xs + stride
            y_maxs = center_ys + stride
            center_gts[..., 0] = torch.where(x_mins > gt_bboxes[..., 0],
                                             x_mins, gt_bboxes[..., 0])
            center_gts[..., 1] = torch.where(y_mins > gt_bboxes[..., 1],
                                             y_mins, gt_bboxes[..., 1])
            center_gts[..., 2] = torch.where(x_maxs > gt_bboxes[..., 2],
                                             gt_bboxes[..., 2], x_maxs)
            center_gts[..., 3] = torch.where(y_maxs > gt_bboxes[..., 3],
                                             gt_bboxes[..., 3], y_maxs)

            cb_dist_left = xs - center_gts[..., 0]
            cb_dist_right = center_gts[..., 2] - xs
            cb_dist_top = ys - center_gts[..., 1]
            cb_dist_bottom = center_gts[..., 3] - ys
            center_bbox = torch.stack(
                (cb_dist_left, cb_dist_top, cb_dist_right, cb_dist_bottom), -1)
            inside_gt_bbox_mask = center_bbox.min(-1)[0] > 0
        else:
            # condition1: inside a gt bbox
            inside_gt_bbox_mask = bbox_targets.min(-1)[0] > 0

        # condition2: limit the regression range for each location
        max_regress_distance = bbox_targets.max(-1)[0]
        inside_regress_range = (
                (max_regress_distance >= regress_ranges[..., 0])
                & (max_regress_distance <= regress_ranges[..., 1]))

        # if there are still more than one objects for a location,
        # we choose the one with minimal area
        areas[inside_gt_bbox_mask == 0] = INF
        areas[inside_regress_range == 0] = INF
        min_area, min_area_inds = areas.min(dim=1)


        ids = gt_ids[min_area_inds]
        ids[min_area == INF] = -1  # set as unannotated
        bbox_targets = bbox_targets[range(num_points), min_area_inds]

        return ids,bbox_targets


# class fby_af_loss(BaseModule):
#     def __init__(self,init_cfg=None):
#         super(fby_af_loss, self).__init__(init_cfg)
#
#     def

def  fby_make_loss(cfg):
    fby_af_loss = fby_af_loss1()
    fby_af_loss.to(device="cuda:0")
    return fby_af_loss.loss


def make_loss_with_center(cfg, num_classes):    # modified by gu
    if cfg.MODEL.NAME == 'resnet18' or cfg.MODEL.NAME == 'resnet34':
        feat_dim = 512
    else:
        feat_dim = 2048

    if cfg.MODEL.METRIC_LOSS_TYPE == 'center':
        center_criterion = CenterLoss(num_classes=num_classes, feat_dim=feat_dim, use_gpu=True)  # center loss

    elif cfg.MODEL.METRIC_LOSS_TYPE == 'triplet_center':
        triplet = TripletLoss(cfg.SOLVER.MARGIN)  # triplet loss
        center_criterion = CenterLoss(num_classes=num_classes, feat_dim=feat_dim, use_gpu=True)  # center loss

    else:
        print('expected METRIC_LOSS_TYPE with center should be center, triplet_center'
              'but got {}'.format(cfg.MODEL.METRIC_LOSS_TYPE))

    if cfg.MODEL.IF_LABELSMOOTH == 'on':
        xent = CrossEntropyLabelSmooth(num_classes=num_classes)     # new add by luo
        print("label smooth on, numclasses:", num_classes)

    def loss_func(score, feat, target):
        if cfg.MODEL.METRIC_LOSS_TYPE == 'center':
            if cfg.MODEL.IF_LABELSMOOTH == 'on':
                return xent(score, target) + \
                        cfg.SOLVER.CENTER_LOSS_WEIGHT * center_criterion(feat, target)
            else:
                return F.cross_entropy(score, target) + \
                        cfg.SOLVER.CENTER_LOSS_WEIGHT * center_criterion(feat, target)

        elif cfg.MODEL.METRIC_LOSS_TYPE == 'triplet_center':
            if cfg.MODEL.IF_LABELSMOOTH == 'on':
                return xent(score, target) + \
                        triplet(feat, target)[0] + \
                        cfg.SOLVER.CENTER_LOSS_WEIGHT * center_criterion(feat, target)
            else:
                return F.cross_entropy(score, target) + \
                        triplet(feat, target)[0] + \
                        cfg.SOLVER.CENTER_LOSS_WEIGHT * center_criterion(feat, target)

        else:
            print('expected METRIC_LOSS_TYPE with center should be center, triplet_center'
                  'but got {}'.format(cfg.MODEL.METRIC_LOSS_TYPE))
    return loss_func, center_criterion